#ifndef __SIMULATED_UART_H
#define __SIMULATED_UART_H

#include <stdbool.h>
#include <stdint.h>
#include "ringbuffer.h"

#define SUART_OK 0
#define SUART_ARGS_NULL 1

#define PIN_HIGH true
#define PIN_LOW false
	
#define TIMER_START true
#define TIMER_STOP false

typedef enum {
	SUART_BAUDRATE_1200 = 1200,
	SUART_BAUDRATE_2400 = 2400,
	SUART_BAUDRATE_4800 = 4800,
	SUART_BAUDRATE_9600 = 9600,
	SUART_BAUDRATE_19200 = 19200,
	SUART_BAUDRATE_38400 = 38400,
	SUART_BAUDRATE_57600 = 57600, 
	SUART_BAUDRATE_115200 = 115200
} suart_baudrate_e;

typedef enum {
	SUART_DATA_BITS_5 = 5,
	SUART_DATA_BITS_6 = 6,
	SUART_DATA_BITS_7 = 7,
	SUART_DATA_BITS_8 = 8
} suart_data_bits_e;

typedef enum {
	SUART_PARITY_NO = 0,
	SUART_PARITY_EVEN = 1,
	SUART_PARITY_ODD = 2,
	SUART_PARITY_SPACE = 3,
	SUART_PARITY_MARK = 4
} suart_parity_e;

typedef enum {
	SUART_STOP_BITS_HALF = 1,
	SUART_STOP_BITS_ONE = 2,
	SUART_STOP_BITS_ONE_AND_HALF = 3,
	SUART_STOP_BITS_TWO = 4
} suart_stop_bits_e;

typedef struct {
	suart_baudrate_e baudrate;
	suart_data_bits_e data_bits;
	suart_parity_e parity;
	suart_stop_bits_e stop_bits;
	uint32_t bit_interval_100ns;
	ringbuffer_t ringbuffer;
	uint32_t half_period_cnt;
	uint8_t recv_byte;
	uint8_t recv_bit_index;
	bool recv_running;
	
	void (*tx_pin_set)(bool high);
	bool (*rx_pin_get)();
	void (*delay_100ns)(uint32_t cnt);
	void (*recv_timer_ctrl)(bool start);
} suart_t;

int suart_init(suart_t *suart, uint8_t *buffer, uint32_t size, 
							void (*tx_pin_set)(bool high), 
							bool (*rx_pin_get)(),
							void (*delay_us)(uint32_t cnt),
							void (*recv_timer_ctrl)(bool start));

void suart_config(suart_t *suart, suart_baudrate_e baudrate,
									suart_data_bits_e data_bits,
									suart_parity_e parity,
									suart_stop_bits_e stop_bits);
							
int suart_send_bytes(suart_t *suart, uint8_t *data, int len);

int suart_receive_bytes(suart_t *suart, uint8_t *data, int len);

void suart_timer_int_handler(suart_t *suart);

void suart_rx_pin_int_handler(suart_t *suart);

#endif

